// pages/store/store.js
import LAN from '../../utils/lan';
const innerAudioContextStore = wx.createInnerAudioContext();
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '',
    nickName: '',
    remoterInfo: null,
    itemImageUrl:["/images/111.png","/images/211.png","/images/311.png","/images/411.png","/images/511.png","/images/611.png","/images/711.png","/images/121.png","/images/221.png","/images/321.png","/images/421.png","/images/521.png","/images/621.png","/images/721.png"],
    itemDescription:["法师","镰刀","剑客","武者","盾兵","大锤","游侠","奇异博士的小披风","耶梦加得之刃","古锭刀","雷电袈裟","大地铠甲","坚毅头巾","大炮"],
    showDescription: false,
    soldout: false,
    coins: 0, //显示的金币数量
    ownedItems: [], // 记录已拥有的商品
    currentItem: null, // 当前上架的商品
    idbtn:"btn3",
    imageUrl: '', // 商品图片路径
    description: '', // 商品描述
    index: 0, // 当前显示的商品索引
  },

  SoldOut: function () {
    this.setData({
      soldout: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    const date = new Date();
    const dayOfWeek = date.getDate(); // 获取当前星期几（0-6，0表示星期日）
  
    const itemIndex = dayOfWeek % 14; // 根据星期信息计算出上架的商品索引
    const itemImageUrl = `/images/${itemIndex + 1}.png`; // 构建商品图片路径
  
    this.setData({
      currentItem: itemImageUrl
    });
  },

  onLoad: function(options) {
    console.log('进入store onLoad')
    var that = this; // 保存this的引用
    const date = new Date();
    const dayOfWeek = date.getDate();
    const itemIndex = dayOfWeek % 14;
    this.setData({
      index: itemIndex,
    });
    const itemImageUrl = ["/images/111.png","/images/211.png","/images/311.png","/images/411.png","/images/511.png","/images/611.png","/images/711.png","/images/121.png","/images/221.png","/images/321.png","/images/421.png","/images/521.png","/images/621.png","/images/721.png"];
    const itemDescription=["法师","镰刀","剑客","武者","盾兵","大锤","游侠","奇异博士的小披风","耶梦加得之刃","古锭刀","雷电袈裟","大地铠甲","坚毅头巾","大炮"];
    const index = 0; // 初始索引
    this.setData({
      imageUrl: itemImageUrl[index],
      description: itemDescription[index],
    });
    wx.getStorage({
      key: 'coins',
      success: function(res) {
        that.setData({
          coins: res.data
        });
        console.log('该用户为老用户，金币为：', res.data);
      },
      fail: function() {
        that.setData({
          coins: 0
        });
      }
    });
  
    setInterval(function() {
      wx.getStorage({
        key: 'coins',
        success: function(res) {
          that.setData({
            coins: res.data
          });
          console.log('该用户为老用户，金币为：', res.data);
        },
        fail: function() {
          that.setData({
            coins: 0
          });
        }
      });
    }, 10000); // 每十秒执行一次，10000毫秒为10秒
  },

  //从后端获得用户的金币数量
  getUserCoins() {
    // 调用后端接口获取用户的金币数量
    // 例如：API.getUserCoins().then(res => {
    //   this.setData({
    //     coins: res.data.coins
    //   });
    // });
    // 这里假设后端接口返回的数据结构为 { coins: 100 }
    var that = this;
    wx.getStorage({
      key: 'coins',
      success: function(res) {
        that.setData({
          coins: res.data
        });
        console.log('该用户为老用户，金币为：', res.data);
      },
      fail: function() {
        that.setData({
          coins: 0
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("进入store onShow")
    // 每次显示页面时，更新用户的金币数量
    this.getUserCoins();
     // 每次显示页面时，更新用户的金币数量和商品的购买情况
     this.getUserCoins();
     var that = this;
     // 从缓存中取出商品的购买情况
     wx.getStorage({
       key: 'ownedItems',
       success: function(res) {
         that.setData({
           ownedItems: res.data
         });
       },
       fail: function() {
         that.setData({
           ownedItems: []
         });
       }
     });


    innerAudioContextStore.src = 'cloud://cloud1-8grlkyuf1058902e.636c-cloud1-8grlkyuf1058902e-1322046947/横田真人 - 青空アスレチック.mp3';
    // 设置自动播放
    innerAudioContextStore.autoplay = false;
    // 设置循环播放
    innerAudioContextStore.loop = true;
    this.getUserCoins();
    
    console.log("into onShow and play store music")
    // 设置音频文件的路径
  
    // 设置音频文件的路径

    // 开始播放音乐
    innerAudioContextStore.play();
    // 监听播放事件
    innerAudioContextStore.onPlay(() => {
    console.log('开始播放');
    });
      // 监听错误事件
    innerAudioContextStore.onError((res) => {
     console.log(res.errMsg);
     console.log(res.errCode);
      });
  },

  onHide() {
    innerAudioContextStore.stop();
    console.log("隐藏store")
    console.log("over store bgm")
  },

  onUnload() {
    wx.setKeepScreenOn({
      keepScreenOn: false,
    })
  },

  onPullDownRefresh() {
  },

  onReachBottom() {
  },

  onShareAppMessage() {
  },

  onClick: function (e) {
    var id = e.target.id;
    if (id == "btn1") {
      let gameVs = this.selectComponent('#game_vs');
      gameVs.resetGame();
    } else if (id == "btn2") {
      if(this.data.ownedItems.includes(this.data.currentItem))
      {
        app.showModal({
          title: '购买失败！',
          content: '您已拥有该角色碎片！请等待新品上架！',
          showCancel: false
        });
      }
      else if (this.data.coins >= 100) {
        app.showModal({
          title: '购买成功！',
          content: '您已拥有该角色碎片！快去前往背包合成角色吧！',
          showCancel: false
        });
        this.setData({
          soldout: true
        });
        this.setData({
          coins: this.data.coins - 100
        });
        this.purchaseItem();
        wx.setStorage({
          key: 'coins',
          data: this.data.coins
        });
      }
      else {
        app.showModal({
          title: '购买失败！',
          content: '金币不足哦，请氪金或者再签到几天吧！',
          showCancel: false
        });
      }
    }
    else if(this.idbtn=="btn3")
    {
      innerAudioContextStore.pause()
      this.idbtn="btn4"
      console.log("btn3情况",this.idbtn)
    }
    else if(id="btn4")
    {
      console.log('into btn3')
      innerAudioContextStore.play()
      this.idbtn="btn3"
      console.log("btn4情况",this.idbtn)
    }
  },

  purchaseItem() {
    this.setData({
      soldout: true
    });
    const ownedItems = this.data.ownedItems;
    ownedItems.push(this.data.currentItem);
  
    this.setData({
      ownedItems: ownedItems
    });

    // 将购买情况更新到缓存中
    wx.setStorage({
      key: 'ownedItems',
      data: ownedItems
    });
  },

  showDescription: function () {
    this.setData({
      showDescription: !this.data.showDescription
    });
  },

  refreshStore: function() {
    var index = this.data.index + 1;
    var itemImageUrl = this.data.itemImageUrl;
    var itemDescription = this.data.itemDescription;
    if (index >= itemImageUrl.length) {
      index = 0;
    }
    this.setData({
      index: index,
      imageUrl: itemImageUrl[index],
      description: itemDescription[index],
      soldout: false, // 当日碎片不再售罄
      currentItem: itemImageUrl[index], // 更新当前上架的商品
    });
  }

  
})